package com.globalwave.base;

import java.sql.Connection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;

import com.globalwave.common.cache.CodeHelper;


public class ConnectionProvider {
	
	private Map<String, StatelessSession> map = new HashMap<String, StatelessSession>() ;
	
    public Connection getConnection(final String dbName) {
    	
    	String factoryName = null ;
    	if (dbName == null || "oracle".equals(dbName)) {
    		factoryName = "sessionFactory" ;
    	} else {
    		factoryName = "sessionFactory_" + dbName ;
    	}
    	
    	StatelessSession session = map.get(factoryName) ;
    	if (session != null) {
    		return session.connection() ;
    	}
    	
    	SessionFactory sf = (SessionFactory)CodeHelper.getAppContext().getBean(factoryName) ;
    	session = sf.openStatelessSession() ;
		map.put(factoryName, session) ;

    	return session.connection() ;
    }
    
    public static Set<String> getDbNames() {
    	Set<String> result = new HashSet<String>() ;
    	result.add("oracle") ;
    	result.add("db2") ;
    	result.add("pos5g") ;
    	return result ;
    }
    
    public Connection getDefaultConnection() {
    	return getConnection("oracle") ;
    }
    
    public void closeAllConnection() {
    	for (StatelessSession s:map.values()) {
    		s.close();
    	}
    }
}
